/*
 * @Description: 
 * @Autor: Zhu_liangyu
 * @Date: 2020-05-09 10:52:56
 */
import Vue from 'vue'
import { ACCESS_TOKEN } from '@/config/storageKey'
import axios from 'axios'
import { Modal } from 'ant-design-vue'
import message from 'ant-design-vue/es/message'
import store from '@/store'

const table_success_code = [60001, 60002, 60003];
const error_code = [10002, 10003, 10004, 10005, 10006, 50000];

// create an axios instance
const service = axios.create({
  baseURL: '/future',
  timeout: 500000
})

// request interceptor
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers['Access-Token'] = Vue.ls.get(ACCESS_TOKEN)
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data
    if (error_code.indexOf(res.code) > -1) {
      if (res.code == 10004 || res.code == 10005) {
        Modal.confirm({
          title: "确认登出",
          content: h => (
            <div>
              <span style="color:red;">{res.msg}</span>
              <span>,可以取消继续留在该页面，或者重新登录</span>
            </div>
          ),
          okText: "重新登录",
          onOk() {
            store.dispatch('user/logout').then(() => {
              location.reload()
            })
          }
        });
      } else {
        let message = res.msg;
        if (res.data) message += res.data;
        Modal.error({
          title: "错误码: " + res.code,
          content: message,
        });
      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      if (table_success_code.indexOf(res.code) > -1) message.success(res.msg)
      return response;
    }
  },
  error => {
    if (error.response) {
      console.log(error.response.msg || error.response.data);
      Modal.error({
        title: error.response.status,
        content: error.response.msg || error.response.data,
      });
    } else {
      console.log(error)
    }
    return Promise.reject(error)
  }
)

export default service
